package com.base.cn.platform.os.service.user.integral;

import com.base.cn.platform.os.common.mybatis.BaseBiz;
import com.base.cn.platform.os.common.mybatis.Pagination;
import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.DateUtils;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.dao.user.integral.CusUserIntegralRecordDao;
import com.base.cn.platform.os.entity.user.integral.CusUserIntegral;
import com.base.cn.platform.os.entity.user.integral.CusUserIntegralRecord;
import com.base.cn.platform.os.entity.user.integral.CusUserIntegralRule;
import com.base.cn.platform.os.entity.user.integral.IntegralRule;
import com.base.cn.platform.os.entity.user.user.CusUser;
import com.base.cn.platform.os.service.user.user.CusUserBiz;
import com.github.pagehelper.PageInfo;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户积分记录
 */
@Service
public class CusUserIntegralRecordBiz extends BaseBiz<CusUserIntegralRecord,CusUserIntegralRecordDao> {

    @Autowired
    private CusUserIntegralRuleBiz cusUserIntegralRuleBiz;
    @Autowired
    private CusUserIntegralBiz cusUserIntegralBiz;
    @Autowired
    private CusUserBiz cusUserBiz;

    /**
     * 添加积分流水记录表
     * @param score  分数
     * @param recordType  记录类型，1 积分消耗  2  积分获取
     * @param description  记录描述
     * @param ruleId 规则id  积分消耗不传
     * @param userId 用户id
     */
    public void addUserIntegralRecord(Integer score, Integer recordType, String description,String actionKey,BigDecimal ruleId, BigDecimal userId,BigDecimal otherId){
        synchronized (userId) {
            CusUserIntegralRecord lastCusUserIntegralRecord = this.findOne(" 1=1 order by createTime desc  ", null);
            CusUserIntegralRecord cusUserIntegralRecord = new CusUserIntegralRecord();
            if (ObjectUtils.isEmpty(lastCusUserIntegralRecord)) {
                cusUserIntegralRecord.setUseScore(score);
                cusUserIntegralRecord.setConsumeScore(0);
                cusUserIntegralRecord.setTotalScore(score);
            }else{
                if (recordType == 1) {// 积分消耗
                    cusUserIntegralRecord.setUseScore(lastCusUserIntegralRecord.getUseScore()-score);
                    cusUserIntegralRecord.setConsumeScore(lastCusUserIntegralRecord.getConsumeScore() + score);
                    cusUserIntegralRecord.setTotalScore(lastCusUserIntegralRecord.getUseScore());
                } else if (recordType == 2) { // 积分获取
                    cusUserIntegralRecord.setUseScore(lastCusUserIntegralRecord.getUseScore()+score);
                    cusUserIntegralRecord.setConsumeScore(lastCusUserIntegralRecord.getConsumeScore());
                    cusUserIntegralRecord.setTotalScore(lastCusUserIntegralRecord.getUseScore()+score);
                    cusUserIntegralRecord.setRuleId(ruleId);
                }
            }

            cusUserIntegralRecord.setOtherId(otherId);
            cusUserIntegralRecord.setScore(score);
            cusUserIntegralRecord.setDescription(description);
            cusUserIntegralRecord.setUserId(userId);
            cusUserIntegralRecord.setRecordType(recordType);
            cusUserIntegralRecord.setRuleKey(actionKey);
            CusUserIntegral cusUserIntegral = cusUserIntegralBiz.updateUserIntegral(score, recordType, userId, actionKey);
            cusUserIntegralRecord.setUserUseScore(cusUserIntegral.getCurrentScore());
            this.save(cusUserIntegralRecord);
        }
        // 修改用户记录统计记录
    }


    /**
     * 创建积分记录对象
     *
     * @param score
     * @param userId
     * @param integralRule 积分规则
     * @return
     */
    public CusUserIntegralRecord createIntegralRecord(Integer score, BigDecimal userId, IntegralRule integralRule, Integer totalScore, Integer userScore, Integer consumerScore, Integer userUseScore) {

        CusUserIntegralRecord cusUserIntegralRecord = new CusUserIntegralRecord();
        cusUserIntegralRecord.setUserId(userId);
        cusUserIntegralRecord.setRuleId(integralRule.getId());
        cusUserIntegralRecord.setRuleKey(integralRule.getKey());
        cusUserIntegralRecord.setRecordType(2);
        cusUserIntegralRecord.setScore(score);
        cusUserIntegralRecord.setDescription(integralRule.getDescription());

        cusUserIntegralRecord.setTotalScore(totalScore);
        cusUserIntegralRecord.setConsumeScore(userScore);
        cusUserIntegralRecord.setUseScore(consumerScore);
        cusUserIntegralRecord.setUserUseScore(userUseScore);
        return cusUserIntegralRecord;
    }



    /**
     * 搜索经验记录列表
     * @param page 分页条件
     * @param cusUserIntegralRecord 查询条件
     * @return PageInfo<CusUserIntegralRecord>
     */
    public PageInfo<CusUserIntegralRecord> queryCusUserIntegralRecordPage(Pagination page,
                                                                         CusUserIntegralRecord cusUserIntegralRecord,
                                                                         List<String> containColumns,boolean integralRule){
        String whereSql = this.whereSql(cusUserIntegralRecord);
        PageInfo<CusUserIntegralRecord> recordPageInfo =  this.findPage(whereSql,page,containColumns);
        List<CusUserIntegralRecord> cusUserIntegralRecordList = recordPageInfo.getList();
        String userIds = cusUserIntegralRecordList.stream().map(e -> String.valueOf(e.getUserId())).collect(Collectors.joining(","));
        if(StringUtils.isNotEmpty(userIds)){
            List<CusUser> cusUserList = cusUserBiz.find("id in (" + userIds + ")", null, null);
            Map<BigDecimal, String> userNikcnameMap = cusUserList.stream().collect(Collectors.toMap(e -> e.getId(), e -> e.getNickname(), (k, v) -> k));
            cusUserIntegralRecordList.stream().forEach(e->{
                String s = userNikcnameMap.get(e.getUserId());
                e.setNickname(s);
            });
        }
        recordPageInfo.setList(cusUserIntegralRecordList);
        if(integralRule){
            recordPageInfo.setList(setUserIntegralRule(recordPageInfo.getList()));
        }
        return recordPageInfo;
    }

    /**
     * 搜索经验记录列表
     * @param count
     * @param cusUserIntegralRecord
     * @return
     */
    public List<CusUserIntegralRecord> queryCusUserIntegralRecordList(Integer count,
                                                                      CusUserIntegralRecord cusUserIntegralRecord,
                                                                      List<String> containColumns,boolean integralRule){
        String whereSql = this.whereSql(cusUserIntegralRecord);
        List<CusUserIntegralRecord> cusUserIntegralRecords =this.find(whereSql,count,containColumns);
        if (integralRule){
            return setUserIntegralRule(cusUserIntegralRecords);
        }
        return cusUserIntegralRecords;
    }

    /**
     * 添加积分规则
     * @param userIntegralRecords
     */
    public List<CusUserIntegralRecord>  setUserIntegralRule(List<CusUserIntegralRecord> userIntegralRecords){
        if(ObjectUtils.isNotEmpty(userIntegralRecords)){
            String ruleIds = "";
            for(CusUserIntegralRecord userIntegralRecord:userIntegralRecords){
                if(!ruleIds.contains(userIntegralRecord.getRuleId().toString())){
                    ruleIds+=userIntegralRecord.getRuleId()+",";
                }
            }
            if(StringUtils.isNotEmpty(ruleIds)){
                ruleIds = StringUtils.subHeadTailString(ruleIds,",");
                List<CusUserIntegralRule> userIntegralRules = cusUserIntegralRuleBiz.find(" id in ("+ruleIds+")",null,new ArrayList<>());
                Map<BigDecimal,CusUserIntegralRule> ruleMap= userIntegralRules.stream().collect(Collectors.toMap(CusUserIntegralRule::getId, u->u));
                for(CusUserIntegralRecord userIntegralRecord:userIntegralRecords){
                    if(ruleMap.get(userIntegralRecord.getRuleId())!=null){
//                        userIntegralRecord.setUserIntegralRule(ruleMap.get(userIntegralRecord.getRuleId()));
                    }
                }
            }
        }
        return userIntegralRecords;
    }

    /**
     * 条件搜索语句
     * @param cusUserIntegralRecord
     * @return
     */
    private String  whereSql(CusUserIntegralRecord cusUserIntegralRecord){
        StringBuilder whereSql = new StringBuilder(" 1 = 1 ");
        if(ObjectUtils.isNotEmpty(cusUserIntegralRecord)){
            if(ObjectUtils.isNotEmpty(cusUserIntegralRecord.getUserId())){
                whereSql .append( " and userId =").append(cusUserIntegralRecord.getUserId());
            }
            if(ObjectUtils.isNotEmpty(cusUserIntegralRecord.getRuleId())){
                whereSql .append(" and ruleId =").append(cusUserIntegralRecord.getRuleId());
            }
            if(ObjectUtils.isNotEmpty(cusUserIntegralRecord.getRuleKey())){
                whereSql .append(" and ruleKey =").append("'"+cusUserIntegralRecord.getRuleKey()+"'");
            }
            if(ObjectUtils.isNotEmpty(cusUserIntegralRecord.getOtherId())){
                whereSql .append( " and otherId=").append(cusUserIntegralRecord.getOtherId());
            }
            if(StringUtils.isNotEmpty(cusUserIntegralRecord.getDescription())){
                whereSql .append( " and description like concat ('%','").append(cusUserIntegralRecord.getDescription()).append("','%')");
            }
            if (StringUtils.isNotEmpty(cusUserIntegralRecord.getRecordType())) {
                whereSql.append(" AND recordType= " + cusUserIntegralRecord.getRecordType());
            }
            if(ObjectUtils.isNotEmpty(cusUserIntegralRecord.getStartDate())){
                String startDate = DateUtils.format(cusUserIntegralRecord.getStartDate(), "yyyy-MM-dd");
                whereSql .append(" and createTime > '").append(startDate).append("'");
            }
            if(ObjectUtils.isNotEmpty(cusUserIntegralRecord.getEndDate())){
                String endDate = DateUtils.format(cusUserIntegralRecord.getEndDate(), "yyyy-MM-dd");
                whereSql .append(" and createTime < '").append(endDate).append("'");
            }
            if (StringUtils.isNotEmpty(cusUserIntegralRecord.getCreateTime())){
                String nowTime = DateUtils.format(cusUserIntegralRecord.getCreateTime(), "yyyy-MM-dd");
                whereSql.append(" and DATE_FORMAT(createTime,'%Y-%m-%d')='").append(nowTime).append("'");
            }

        }
        whereSql .append(" order by updateTime desc");
        return whereSql.toString();
    }
}
